package com.suishoupai.xmb.service;

import com.suishoupai.xmb.Security.MyUserDetail;
import com.suishoupai.xmb.dao.BlacklistMapper;
import com.suishoupai.xmb.dao.CutBlacklistMapper;
import com.suishoupai.xmb.dao.CutUserMapper;
import com.suishoupai.xmb.entity.Blacklist;
import com.suishoupai.xmb.entity.CutBlacklist;
import com.suishoupai.xmb.entity.RoleEnum;
import com.suishoupai.xmb.entity.User;
import com.suishoupai.xmb.exception.XmbException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by caojian on 2017/4/18.
 */
@Service
public class BlacklistService {
    @Autowired
    private BlacklistMapper blacklistMapper;
    @Autowired
    private CutBlacklistMapper cutBlacklistMapper;
    @Autowired
    private SessionRegistry sessionRegistry;
    @Autowired
    private CutUserMapper cutUserMapper;

    public List<CutBlacklist> getAll() {
        return cutBlacklistMapper.selectAll();
    }

    /**
     * 添加进黑名单
     *
     * @param blacklist
     */
    @Transactional
    public void add(Blacklist blacklist) throws XmbException {
        long userId = blacklist.getUserId();
        //检查
        if (this.isExist(userId)) {
            throw XmbException.newRepeatRequest();
        }
        User user = cutUserMapper.selectByPrimaryKey(userId);
        if (user.getRole().equals(RoleEnum.ADMIN.getValue())) {
            throw XmbException.newError("不能将管理员加入黑名单！");
        }
        //操作
        blacklist.setCreateTime(System.currentTimeMillis());
        if (blacklistMapper.insertSelective(blacklist) == 0) {
            throw new RuntimeException("插入失败！");
        }
        //踢出登录
        List<Object> principals = sessionRegistry.getAllPrincipals();
        for (Object principal : principals) {
            MyUserDetail myUserDetail = (MyUserDetail) principal;
            if (myUserDetail.getUser().getId() == userId) {
                List<SessionInformation> sis = sessionRegistry.getAllSessions(principal, false);
                if (sis != null) {
                    for (SessionInformation si : sis) {
                        si.expireNow();
                    }
                }
            }
        }
    }

    /**
     * 移除黑名单
     *
     * @param userId
     */
    public void del(long userId) throws XmbException {
        //检查
        if (!this.isExist(userId)) {
            throw XmbException.newRepeatRequest();
        }

        if (cutBlacklistMapper.deleteByPrimaryKey(userId) == 0) {
            throw new RuntimeException("删除失败！");
        }
    }

    /**
     * 该用户是否已存在黑名单中
     *
     * @param userId
     */
    public boolean isExist(long userId) {
        return cutBlacklistMapper.selectByPrimaryKey(userId) != null;
    }
}
